package lesson9;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MyLock {

    public static void main(String[] args) throws InterruptedException {

        PrintQueue printQueue = new PrintQueue();

        Thread[] thread = new Thread[10];

        for(int i = 0; i < 10; i++){
            thread[i] = new Thread(new PrintObject(printQueue), "thread-" + i);
        }

        for(int i = 0; i < 10; i++){
            thread[i].start();
            Thread.sleep(100);
        }
    }

    static class PrintObject implements Runnable{

        PrintQueue printQueue;

        PrintObject(PrintQueue printQueue){
            this.printQueue = printQueue;
        }

        @Override
        public void run() {
            System.out.printf("%s: Going to print a job\n", Thread.currentThread().getName());
            printQueue.printDocument(new Object());
            System.out.printf("%s: The document has been printed\n", Thread.currentThread().getName());
        }
    }

    static class PrintQueue{

        private Lock lock = new ReentrantLock(false);

        public void printDocument(Object document){

            lock.lock();
            try {

                Long duration = (long) (Math.random() * 10000);

                System.out.printf("%s: PrintQueue: Printing a Job during %d seconds\n", Thread.currentThread().getName(), (duration / 1000));

                Thread.sleep(duration);

            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }

            lock.lock();
            try {

                Long duration = (long) (Math.random() * 10000);

                System.out.printf("%s: PrintQueue: Printing a Job during %d seconds\n", Thread.currentThread().getName(), (duration / 1000));

                Thread.sleep(duration);

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }

    }
}
